import axios from "axios";
import {store} from "../redux";

axios.defaults.baseURL = 'http://localhost:9999/api';
axios.defaults.timeout = 50000;
axios.defaults.withCredentials = false;
axios.defaults.headers.post['Content-Type'] = 'application/json';

axios.interceptors.request.use((config) => {
    config.headers = {
        "Authorization": store.getState().user.token
    }
    return config;
})

axios.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        const response = error.response;
        return Promise.reject(response || {message: error.message})
    }
)

export interface Result<T> {
    code: number;
    msg: string;
    data: T;
}

export interface PageData<T> {
    records: T[];
    page: number;
    size: number;
    total: number;
}

// 分页返回
export type PageResult<T> = Result<PageData<T>>



const httpGet = async <T, E>(url: string, param?: E): Promise<T> => {
    const {data} = await axios.get<T>(url, {params: param})
    // console.log("httpGet", data);
    return data
}

const httpPost = async <T, E>(url: string, param: E): Promise<T> => {
    const {data} = await axios.post<T>(url, param)
    // console.log("httpPost", data);
    return data
}

const httpDelete = async <T, E>(url: string, param: E): Promise<T> => {
    const {data} = await axios.delete(url, {params: param})
    return data
}

const httpFormPost = async <T, E>(url: string, params?: E): Promise<T> => {
    const {data} = await axios.post(url, params, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
    return data
}

export {httpGet, httpPost, httpDelete, httpFormPost}
